package com.mycase.im.boot.websocket.pattern.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mycase.im.boot.entity.communication.ClientMessage;
import com.mycase.im.boot.entity.communication.ResponseMessage;
import com.mycase.im.boot.entity.database.ImUser;
import com.mycase.im.boot.entity.database.ImUserFriend;
import com.mycase.im.boot.service.UserFriendService;
import com.mycase.im.boot.service.UserService;
import com.mycase.im.boot.websocket.WebSocketSignal;
import com.mycase.im.boot.websocket.pattern.MessageStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.util.List;
import java.util.Map;

/**
 * 用于修改个人消息的策略器
 * @Author ZhuHJay
 * @Date 2021/9/29 15:09
 */
@Slf4j
@Service
public class UpdateInformation implements MessageStrategy {

    @Autowired
    private UserService userService;
    @Autowired
    private UserFriendService userFriendService;

    @Override
    public Boolean isUse(int type) {
        return WebSocketSignal.MESSAGE_UPDATE_MINE_INFORMATION == type;
    }

    @Override
    public void executeHandler(ClientMessage clientMessage,
                               ObjectMapper objectMapper,
                               Map<String, Session> clientMaps,
                               Session mySession) throws Exception {
        log.warn("修改个人消息的策略");

        // 获取发起人的信息
        ImUser userInfoById = userService.getUserInfoById(clientMessage.getFromId());
        // 获取发送人的好友列表(在这里我只需要好友的id即可)
        List<ImUserFriend> friendList = userFriendService.getFriendList(clientMessage.getFromId());
        ResponseMessage responseMessage = ResponseMessage.success()
                .appendData("userInfo", userInfoById)
                .appendData("type", WebSocketSignal.MESSAGE_UPDATE_MINE_INFORMATION);
        // 将数据发送出去
        sendMessage(objectMapper, mySession, responseMessage);
        for (ImUserFriend imUserFriend : friendList) {
            if( clientMaps.containsKey(imUserFriend.getFriendId()) ){
                sendMessage(
                        objectMapper,
                        clientMaps.get(imUserFriend.getFriendId()),
                        responseMessage);
            }
        }
    }

}
